<template>
  <view class="content" id="content" ref="content">
    <view class="title">
      <image
        src="../../static/jiantous.png"
        mode=""
        style="
          width: 32rpx;
          height: 32rpx;
          margin-left: 30rpx;
          z-index: 999;
          position: absolute;
        "
        @click="returns()"
      ></image>
    </view>

    <view>
      <image
        src="../../static/lighting.png"
        style="
          position: absolute;
          left: 50%;
          transform: translate(-50%, -10%);
          z-index: 2;
        "
      ></image>
    </view>

    <view id="threeView" style="z-index: 99; position: absolute"></view>

    <view>
      <view :threeall="threeall" :change:threeall="three.all"></view>
      <view class="base">
        <image class="base_image" src="../../static/detail_base.png"></image>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      threeall: {
        width: "",
        productDetail_url: "",
        height: "",
        is_picture: false,
        picture: "",
        is_shanghu: uni.getStorageSync("unique_code"),
        shanghu_bg: "",
      },
    };
  },
  onLoad(options) {
    this.$nextTick(() => {
      uni.getSystemInfo({
        success: (res) => {
          this.threeall.productDetail_url = JSON.parse(
            options.threeall
          ).productDetail_url;
          this.threeall.is_picture = JSON.parse(options.threeall).is_picture;
          if (this.threeall.is_picture) {
            this.threeall.picture = options.picture;
          }
          this.threeall.width = res.safeArea.width;
          this.threeall.height = res.safeArea.height;
        },
      });
    });
  },
  onShow() {
    this.getImage();
  },
  methods: {
    returns() {
      let canNavBack = getCurrentPages();
      if (canNavBack && canNavBack.length > 1) {
        uni.navigateBack({
          delta: 1,
        });
      } else {
        history.back();
      }
    },
    async getImage() {
      if (!this.threeall.is_shanghu) {
        return;
      }
      let res = await api.getImage({
        method: "get",
        query: {},
      });

      if (res.code === 0) {
        this.threeall.shanghu_bg = res.data.url;
      } else {
        tip.defaults(res.msg);
      }
    },
  },
};
</script>

<script module="three" lang="renderjs">
	const THREE = require('static/three/build/three.min.js')
	
	// OrbitControls 是对 Threejs 的三维场景进行缩放、平移、旋转操作
	import {
		OrbitControls
	} from 'static/three/examples/jsm/controls/OrbitControls.js'

	// 导入 glb 格式模型，若要导入其他格式模型，可尝试在 loaders 目录下加载其他文件
	import {
		GLTFLoader
	} from 'static/three/examples/jsm/loaders/GLTFLoader.js'
  import { RGBELoader } from 'static/three/examples/jsm/loaders/RGBELoader.js';

	var renderer;
	var scene;
	var camera;
	var controls;

	export default {
    props: {
      url: ""
    },
    onUnload(){
      renderer = null
      scene = null
      camera = null
      controls = null
    },
		mounted() {
			// this.initThree();//加载场景
			// this.leadModel(resources_url);//导入模型
			// this.createControls();//控制模型的缩放、平移、旋转操作
		},
		methods: {
      all(newValue, oldValue, ownerInstance, instance){
        if(newValue.productDetail_url==""){
          return
        }
        console.log('all执行');
        this.initThree(newValue);//加载场景
		  	this.leadModel(newValue);//导入模型
		  	this.createControls();//控制模型的缩放、平移、旋转操作
      },
			createControls() {
				controls = new OrbitControls(camera, renderer.domElement)
        //滚轮是否可控制zoom
        controls.enableZoom = true;
        // controls.maxZoom
        // controls.minDistance = 2;
        // controls.maxDistance = 15;
        //是否自动旋转
        controls.autoRotate = true;
        controls.autoRotateSpeed = 2.0;

        //是否可平移，默认移动速度为7px
        controls.enablePan = false;

        //鼠标控制是否可用
        // controls.enabled = false;

        // //上下翻转的最大角度
        // controls.maxPolarAngle = 1.55;

        // //上下翻转的最小角度
        // controls.minPolarAngle = 1.55;
			},

			// 导入模型
			leadModel(newValue) {
				let loader = new GLTFLoader();
				// 导入本地或者服务器上的模型都可以
        
				loader.load(newValue.productDetail_url, function(gltf) {
					// loader.load('https://threejs.org/examples/models/gltf/RobotExpressive/RobotExpressive.glb', function(gltf) {
            // http://img.yunshiar.com/models/niuniu.gltf

          gltf.scene.scale.set(0.5, 0.5, 0.5);

          // gltf.scene.traverse( function ( child ) {
          //   if ( child.isMesh ) {
          //     child.material.emissive = new THREE.Color(0x414141);
          //     child.material.emissiveMap = child.material.map;
          //     child.material.emissiveIntensity = 0.1;
          //     child.material.metalness = 1;
          //     child.material.roughness = 1;
          //   }
          // });

          if(newValue.is_picture){
            {
              var geometry = new THREE.PlaneGeometry(22,22); //矩形平面
              var textureLoader = new THREE.TextureLoader();

              // 执行load方法，加载纹理贴图成功后，返回一个纹理对象Texture
              textureLoader.load(newValue.picture, function(texture) {
                texture.encoding = THREE.sRGBEncoding;
                var material = new THREE.MeshLambertMaterial({
                  // color: 0x0000ff,
                  // 设置颜色纹理贴图：Texture对象作为材质map属性的属性值
                  map: texture,//设置颜色贴图属性值
                });
                var mesh = new THREE.Mesh(geometry, material); //网格模型对象Mesh
                // mesh.rotateY(0.176);

                // mesh.translateY(3.1);
                // mesh.translateZ(0.65);
                // mesh.translateX(-0.1);
                scene.add(mesh); //网格模型添加到场景中
              });
            }
            if(newValue.is_shanghu){
              var geometry1 = new THREE.PlaneGeometry(43,43); //矩形平面
              var textureLoader1 = new THREE.TextureLoader();

              // 执行load方法，加载纹理贴图成功后，返回一个纹理对象Texture
              textureLoader1.load(newValue.shanghu_bg, function(texture) {
                texture.encoding = THREE.sRGBEncoding;
                var material = new THREE.MeshLambertMaterial({
                  // color: 0x0000ff,
                  // 设置颜色纹理贴图：Texture对象作为材质map属性的属性值
                  map: texture,//设置颜色贴图属性值
                });
                var mesh = new THREE.Mesh(geometry1, material); //网格模型对象Mesh
                let planeMat = new THREE.MeshBasicMaterial;
                planeMat.side=THREE.DoubleSide;
                mesh.rotateY(3.14159274);

                // mesh.translateY(3.1);
                mesh.translateZ(2.5);
                // mesh.translateX(-0.1);
                // mesh.position.set(22,0,10)

                scene.add(mesh); //网格模型添加到场景中
              });
            }
          }

					scene.add(gltf.scene);

				});
			},

			initThree(newValue) {
				// 如果返回的不是未定义，说明threejs成功引入
				console.log('打印场景API', THREE.Scene);

				/* 创建场景对象Scene */
				scene = new THREE.Scene();

        // 环境灯
        // THREE.AmbientLight不需要指定位置，只需要指定颜色（十六进制）
        var ambientLight = new THREE.AmbientLight(0xffffff, 0.3)
        scene.add(ambientLight)

        // 主光
        const mainlLight = new THREE.DirectionalLight(0xffffff,  0.5)
        mainlLight.position.set(0, 0, 25);
        scene.add(mainlLight);

        // 背光
        const backlLight = new THREE.DirectionalLight(0xffffff, 0.5)
        backlLight.position.set(0, 0, -25);
        scene.add(backlLight);

        // // 底光
        // const bottomlLight = new THREE.DirectionalLight(0xffffff, 0.1)
        // bottomlLight.position.set(0, -50, 25);
        // scene.add(bottomlLight);

				/*
				    相机设置
				 */
				// var width = window.innerWidth; // 窗口宽度
				// var height = window.innerHeight; // 高度
				var width = newValue.width; // 窗口宽度
				var height = newValue.height; // 高度
				var k = width / height; // 窗口宽高比
				var s = 1000; // 三维场景显示范围控制系数，系数越大，显示的范围越大
				// 创建相机对象（正射投影）
				camera = new THREE.PerspectiveCamera(45, k, 1, 1000);
        if(newValue.is_picture){
          camera.position.set(0, 0, 100); //设置相机的摆放位置
        }else{
          camera.position.set(0, 0, 5); //设置相机的摆放位置
        }
				// camera.lookAt(new THREE.Vector3(0, 0, 0)); // 控制相机的焦点(镜头)位置，决定相机的朝向（取值为3维坐标对象-THREE.Vector3(x,y,z)）

				/*
				    创建渲染器对象
				 */
				renderer = new THREE.WebGLRenderer({
					antialias: true,   //抗锯齿
					alpha: true //设置透明，为true时，背景颜色需要注释掉
				});

        renderer.toneMapping = THREE.NoToneMapping;
        renderer.textureEncoding = THREE.sRGBEncoding;
        renderer.outputEncoding = THREE.sRGBEncoding;
        renderer.setPixelRatio(window.devicePixelRatio); //开启HiDPI
        renderer.setSize(window.innerWidth, window.innerHeight);
				renderer.setSize(width, height); // 设置渲染区域尺寸
				// renderer.setClearColor(0XECF1F3, 1); // 设置背景颜色

        // 环境贴图HDR
        new RGBELoader().load('https://img.metatmt.com/model/venice_sunset_1k.hdr', (texture) => {
          const pmremGenerator = new THREE.PMREMGenerator(renderer);
          const envMap = pmremGenerator.fromEquirectangular(texture).texture;
          pmremGenerator.dispose();
          scene.environment = envMap;
          // scene.background = envMap
        });

				const element = document.getElementById('threeView')
				element.appendChild(renderer.domElement); // body元素中插入canvas对象

        // var geometry = new THREE.PlaneGeometry(8.7,8.7); //矩形平面
        // var textureLoader = new THREE.TextureLoader();

        // // 执行load方法，加载纹理贴图成功后，返回一个纹理对象Texture
        // textureLoader.load(this.productDetail.resources_url, function(texture) {
        //   var material = new THREE.MeshLambertMaterial({
        //     // color: 0x0000ff,
        //     // 设置颜色纹理贴图：Texture对象作为材质map属性的属性值
        //     map: texture,//设置颜色贴图属性值
        //   });
        //   var mesh = new THREE.Mesh(geometry, material); //网格模型对象Mesh
        //   // mesh.rotateY(0.176);

        //   // mesh.translateY(3.1);
        //   // mesh.translateZ(0.65);
        //   // mesh.translateX(-0.1);
        //   scene.add(mesh); //网格模型添加到场景中
        // });

        
        // var geometry = new THREE.PlaneGeometry(8.7,8.7); //矩形平面
        // var material = new THREE.MeshLambertMaterial({
        //   color: 0x000000, //三角面颜色
        //   transparent: true,  
        //   opacity : 0.1      
        // }); //材质对象
        // var mesh = new THREE.Mesh(geometry, material); //网格模型对象Mesh
        //  scene.add(mesh); //网格模型添加到场景中

				// 执行渲染操作，指定场景，相机作为参数
				renderer.render(scene, camera);
        //  console.log(animationstatr,'this.animationstatr');
				this.render();
			},

			// 动画
			render() {
        if (!scene) {
          return
        }
        // scene.rotateY(0.006);//每次绕y轴旋转0.01弧度
        // scene.rotateZ(0.01);//每次绕Z轴旋转0.01弧度
        // scene.rotateX(0.01);//每次绕X轴旋转0.01弧度

        requestAnimationFrame(() => {
          this.render();
        });

        renderer.render(scene, camera); //执行渲染操作
			},

		}
	}
</script>

<style lang="scss" scoped>
@import "../../style/yuanchuang.scss";
.content {
  font-family: PingFangSC-Regular, PingFang SC;
  // padding: 30rpx 0 200rpx 0;
  background: $bg-color1;
  min-height: 100vh;
  z-index: -99;
}
.title {
  position: absolute;
  top: 86rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.base {
  position: absolute;
  bottom: 0px;
  margin: -60rpx 74rpx 0 74rpx;
  z-index: 2;
  &_image {
    width: 670rpx;
    height: 360rpx;
  }
}
</style>
